<template>
    <div class="login-page">
        <h2>Server Inspect</h2>
        <div class="login-form-container">
            <h2>登录</h2>
            <el-form :model="formData" :rules="rules" ref="formRef" @keyup.enter.native="onSubmit(formRef)">
                <el-form-item prop="username">
                    <el-input v-model="formData.username" placeholder="请输入账号" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit(formRef)" class="login-btn">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import net from '@/util/net'
import { useRouter } from 'vue-router'

const formRef = ref()

const router = useRouter()

const rules = reactive({
    username: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
})

const formData = reactive({
    username: '',
    password: '',
})

const onSubmit = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            net.request('/security/login', formData).then(res => {
                if (res) {
                    localStorage.setItem('access_token', res.access_token)
                    localStorage.setItem('refresh_token', res.refresh_token)
                    ElMessage({
                        message: '登录成功',
                        type: 'success',
                        plain: true,
                    })
                    router.push('/')
                }
            })
        }
    })
}
</script>

<style lang="scss" scoped>
.login {
    &-page {
        width: 100%;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        background-color: #2d3a4b;
        color: #fff;
    }

    &-form-container {
        width: 300px;
        border: 1px solid #fff;
        background: rgba(255, 255, 255, .1);
        padding: 40px 30px;
        border-radius: 10px;

        h2 {
            text-align: center;
            margin-top: 0;
        }
    }

    &-btn {
        width: 100%;
    }
}

:deep(.el-form-item__label) {
    color: #fff;
}
</style>